import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { PrismaService } from 'src/common/prisma/prisma.service'
import { policy_key } from './roles.decorator'
import { Request } from 'express'

@Injectable()
export class RolesGuard implements CanActivate {
   constructor(private reflector: Reflector, private prisma: PrismaService) {}
   async canActivate(context: ExecutionContext): Promise<boolean> {
      // xx.policy.ts中的类名是控制的名字
      const { db, policy } = this.reflector.get(policy_key, context.getHandler())

      // 获取xx.policy.ts中的方法名与控制器同名
      const method = context.getHandler().name

      const request = context.switchToHttp().getRequest() as Request

      const policyInstance = new policy(this.prisma, request)

      return policyInstance[method](db)
   }
}
